package com.topInterview;

/**
 * 从旋转排序数组查找某数
 *
 * @Author: huangzhigao
 * @Date: 2022/2/19 16:27
 */
public class Leecode33_findNumInReverseArr {
    public int search(int[] nums, int target) {
        if (nums == null || nums.length < 1) {
            return -1;
        }

        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (right + left) >> 1;
            if (nums[mid] == target) {
                return mid;
            }
            //如果 left right mid 值都相等的情况 且mid的值不等于target
            if (nums[left] == nums[mid] && nums[right] == nums[mid]) {
                while (left != mid && nums[left] == nums[mid]) {
                    left++;
                }
                //left==mid 或者nums[left]!=nums[mid]
                if (left == mid) {
                    //left已经来到mid位置，二分从mid+1~right继续二分
                    left = mid + 1;
                    continue;
                }
            }

            //left mid right不都一样
            if (nums[left] != nums[mid]) {
                if (nums[mid] > nums[left]) {
                    if (target >= nums[left] && target <nums[mid]) {
                        right = mid - 1;
                    } else {
                        left = mid +1;
                    }

                } else {
                    if (target > nums[mid] && target <= nums[right]) {
                        //target比有序数据中最小值还大，则在右半部
                        left = mid + 1;
                    } else {
                        //左侧继续二分
                        right = mid - 1;
                    }
                }
            } else {
                //nums[right] != nums[mid] && L==M
                if (nums[mid] < nums[right]) {
                    //右侧有序
                    if (target > nums[mid] && target <= nums[right]) {
                        left = mid + 1;
                    } else {
                        right = mid - 1;
                    }
                } else {
                    //左侧有序
                    if (target >= nums[left] && target < nums[mid]) {
                        right = mid - 1;
                    } else {
                        left = mid + 1;
                    }
                }
            }

        }

        return -1;


    }
}
